package com.csx.saas.platform.system.service.impl;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.csx.basic.base.service.SuperServiceImpl;
import com.csx.basic.database.mybatis.conditions.Wraps;
import com.csx.saas.platform.system.dao.SystemUserRoleMapper;
import com.csx.saas.platform.system.dto.SaveUserRoleDTO;
import com.csx.saas.platform.system.entity.SystemUserRole;
import com.csx.saas.platform.system.service.SystemUserRoleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 业务实现类
 * 角色分配
 * 账号角色绑定
 * </p>
 *
 * @author ChenSongXin
 * @date 2021-02-07
 */
@Slf4j
@Service
@DS("#thread.tenant")
public class SystemUserRoleServiceImpl extends SuperServiceImpl<SystemUserRoleMapper, SystemUserRole> implements SystemUserRoleService {
    @Override
    public void saveUserRole(SaveUserRoleDTO saveUserRoleDTO) {
        Long userId = saveUserRoleDTO.getUserId();
        List<Long> roleId = saveUserRoleDTO.getRoleId();
        //清除授权的角色
        remove(Wraps.<SystemUserRole>lbQ().eq(SystemUserRole::getUserId, userId));
        //保存新授权的资源
        if(!roleId.isEmpty() && roleId.size()>0){
            List<SystemUserRole> systemUserRoleList = roleId.stream().map(id -> {
                SystemUserRole systemUserRole = SystemUserRole.builder().roleId(id).userId(userId).build();
                return systemUserRole;
            }).collect(Collectors.toList());
            saveBatch(systemUserRoleList);
        }
    }
}
